package com.ymj.netty.server.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ymj.netty.common.Response;
import com.ymj.netty.common.ServerRequest;
import com.ymj.netty.server.medium.Medium;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.commons.lang.StringUtils;

/**
 *  @Description:
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
@ChannelHandler.Sharable
public class BizServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        System.out.println("server received:["+msg+"]");
        if(StringUtils.isBlank((String)msg)){
            return;
        }
        //处理心跳
        if("pong".equals(msg)){
            System.out.println(msg);
        }
        //接收到客户端请求
        ServerRequest serverRequest = JSONObject.parseObject((String)msg, ServerRequest.class);
        Medium medium = Medium.getInstance();
        Object result = medium.process(serverRequest);  //反射调用对应业务方法
        Response response = new Response();
        response.setId(serverRequest.getId());
        response.setContent(result);
        ctx.channel().writeAndFlush(JSON.toJSONString(response));
        ctx.channel().writeAndFlush("\r\n");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //处理心跳事件
        if(evt instanceof IdleStateEvent){
            if(((IdleStateEvent) evt).state().equals(IdleState.READER_IDLE)){
                //读空闲
                System.out.println("----读空闲-----");
                ctx.channel().close();
            }else if(((IdleStateEvent) evt).state().equals(IdleState.WRITER_IDLE)){
                System.out.println("-----写空闲-----");
            }else if(((IdleStateEvent) evt).state().equals(IdleState.ALL_IDLE)){
                ctx.writeAndFlush("ping\r\n");
            }
        }
    }
}
